// mqttService.ts
import mqtt from 'mqtt'

let client = null
export function initMQTT() {
  const options = {
    connectTimeout: 4000,
    clientId: 'vue3_client_' + Math.random().toString(16).substr(2, 8),
    username: 'admin',
    password: 'Hhuc1115',
    keepalive: 60,
    clean: true,
  }

  client = mqtt.connect('mqtt://iot.zn-power.com:30107/mqtt', options)

  client.on('connect', () => {
    console.log('✅ MQTT connected')
    client.subscribe('test/topic')
  })

  client.on('message', (topic, message) => {
    console.log(`📩 MQTT message: ${topic} => ${message.toString()}`)
  })
}

export function publish(topic, payload) {
  if (client?.connected) {
    client.publish(topic, payload)
  } else {
    console.warn('❗MQTT not connected.')
  }
}

export function subscribe(topic) {
  if (client?.connected) {
    client.subscribe(topic)
  }
}
